package com.lipuwater.agent.ui.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.ismartlib.framework.permissions.Permission;
import com.ismartlib.framework.permissions.PermissionsResult;
import com.ismartlib.framework.permissions.ResultCallBack;
import com.ismartlib.utils.NetUtils;
import com.lipuwater.agent.R;
import com.lipuwater.agent.app.base.ui.BaseLayoutActivity;
import com.lipuwater.agent.http.ApiCallBack;
import com.lipuwater.agent.http.HttpConfig;
import com.lipuwater.agent.http.ResponseParams;
import com.lipuwater.agent.http.api.ApiRequestsBasis;
import com.lipuwater.agent.http.bean.mall.OrderInfoBean;
import com.lipuwater.agent.http.bean.product.ProductInfoBean;
import com.lipuwater.agent.ui.utils.CityChooseUtils;
import com.lipuwater.agent.ui.utils.MallActivityList;
import com.lipuwater.agent.utils.LoaderImage;
import com.lipuwater.agent.utils.MapToBeanUtil;
import com.lipuwater.agent.utils.PriceUtils;
import com.lipuwater.agent.utils.onclick.NoDoubleClick;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;


public class ProduceOrderActivity extends BaseLayoutActivity implements CityChooseUtils.CallBack, View.OnClickListener {

    @Bind(R.id.text_city)
    EditText textCity;
    @Bind(R.id.text_choose)
    TextView textChoose;
    @Bind(R.id.edit_client_name)
    EditText editClientName;
    @Bind(R.id.edit_client_phone)
    EditText editClientPhone;
    @Bind(R.id.edit_user)
    EditText editUser;
    @Bind(R.id.edit_user_phone)
    EditText editUserPhone;
    @Bind(R.id.edit_detail_address)
    EditText editDetailAddress;
    @Bind(R.id.text_deposit)
    TextView textDeposit;
    @Bind(R.id.text_price)
    TextView textPrice;
    @Bind(R.id.text_all_price)
    TextView textAllPrice;
    @Bind(R.id.image_devide_img)
    ImageView imageDevideImg;
    @Bind(R.id.text_device_name)
    TextView textDeviceName;
    @Bind(R.id.text_device_normsid)
    TextView textDeviceNormsid;
    @Bind(R.id.text_rent_name)
    TextView textRentName;
    @Bind(R.id.checkBox)
    CheckBox checkBox;
    @Bind(R.id.text_agreement)
    TextView textAgreement;
    @Bind(R.id.text_prompt)
    TextView textPrompt;

    private String addressCode = "";
    /**
     * 接收上一页传过来的产品详情
     */
    private ProductInfoBean mProductInfoBean;
    private String mProImgUrl;
    private String mProName;
    private String mNormsidName;

    private NoDoubleClick mNoDoubleClick = new NoDoubleClick();

    private int mOrderId;
    private int mOptionId;
    private int mRentId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MallActivityList.getInstance().addActivity(this);
        setMyContentView(R.layout.activity_produce_order);
        viewToolbarShadow.setVisibility(View.VISIBLE);
        initTitle(R.drawable.icon_aleft, "开户");
        ButterKnife.bind(this);
        try {
            mProductInfoBean = (ProductInfoBean) getIntent().getSerializableExtra("product");
            if (mProductInfoBean == null) {
                showNoNetWork();
                emptyLayout.setOnClickListener(this);
                return;
            }
            mProImgUrl = mProductInfoBean.getImgUrl();
            mProName = mProductInfoBean.getContent();
            mNormsidName = mProductInfoBean.getOptionName();
            LoaderImage.onLoadingImage(mProImgUrl, imageDevideImg, R.drawable.img_loading);
            textDeviceName.setText(mProName);
            textDeviceNormsid.setText("规格分类：" + mNormsidName);
            textDeposit.setText(PriceUtils.changeF2Y(Long.valueOf(mProductInfoBean.getDeposit())));
            textRentName.setText(mProductInfoBean.getRentName());
            long total = mProductInfoBean.getPrice() + mProductInfoBean.getDeposit();
            textPrice.setText(PriceUtils.changeF2Y(mProductInfoBean.getPrice()));
            textAllPrice.setText("合计：" + PriceUtils.changeF2Y(total));

            mOrderId = mProductInfoBean.getId();
            mOptionId = mProductInfoBean.getOptionId();
            mRentId = mProductInfoBean.getRentId();
        } catch (Exception e) {
            showNoNetWork();
            emptyLayout.setOnClickListener(this);
        }
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    textAgreement.setTextColor(ContextCompat.getColor(ProduceOrderActivity.this, R.color.themeColor));
                } else {
                    textAgreement.setTextColor(0xffb3b3b3);
                }
            }
        });
        //监听客户手机输入内容变化
        editClientPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 11) {
                    if (editClientPhone.getText().toString().matches("[1][3458]\\d{9}")) {
                        checkCustomerPhone();
                    } else {
                        textPrompt.setText("");
                    }
                } else {
                    textPrompt.setText("");
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        MallActivityList.getInstance().removeActivity(this);
        ButterKnife.unbind(this);
        ApiRequestsBasis.cancelRequests(this);
    }


    @OnClick({R.id.text_agreement, R.id.text_city, R.id.layout_city, R.id.btn_order_des})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.text_agreement:
                if (mNoDoubleClick.check()) return;
                Intent intent = new Intent(this, WebViewActivity.class);
                intent.putExtra("title", "使用协议");
                intent.putExtra("url", HttpConfig.TOS_TRIPARTITE);
                startActivity(intent);
                break;
            case R.id.text_city:
                if (mNoDoubleClick.check()) return;
                PermissionDialog();
                break;
            case R.id.layout_city:
                if (mNoDoubleClick.check()) return;
                PermissionDialog();
                break;
            case R.id.btn_order_des:
                if (mNoDoubleClick.check()) return;
                if (!checkBox.isChecked()) {
                    Toast("请阅读并同意三方使用协议");
                    return;
                }
                if (editClientName.getText().toString().equals("")) {
                    Toast("请输入客户名称");
                    return;
                }
                if (TextUtils.isEmpty(editClientPhone.getText().toString())) {
                    Toast("请输入手机号码");
                    return;
                } else if (!editClientPhone.getText().toString().matches("[1][3458]\\d{9}")) {
                    Toast("手机号码格式输入有误");
                    return;
                }
                if (editClientPhone.getText().toString().equals("")) {
                    Toast("请输入客户手机号码");
                    return;
                }
                if (editUser.getText().toString().equals("")) {
                    Toast("请输入收件人姓名");
                    return;
                }
                if (TextUtils.isEmpty(editUserPhone.getText().toString())) {
                    Toast("请输入收件人手机号码");
                    return;
                } else if (!editUserPhone.getText().toString().matches("[1][3458]\\d{9}")) {
                    Toast("手机号码格式输入有误");
                    return;
                }
                if (textCity.getText().toString().equals("")) {
                    Toast("请选择收货地址");
                    return;
                }
                if (editDetailAddress.getText().toString().equals("")) {
                    Toast("请输入详细地址");
                    return;
                }
                postOrder();
                break;
        }
    }

    @Override
    public void chooseResults(List<String> results, List<String> resultsCode) {
        String resultsStr = "";
        for (int i = 0; i < results.size(); i++) {
            resultsStr += results.get(i) + "";
            addressCode += resultsCode.get(i) + "|";
        }
        addressCode.substring(0, addressCode.length() - 1);
        textCity.setText(resultsStr);
        textChoose.setVisibility(View.GONE);
    }

    private void postOrder() {
        Map<String, Object> params = new HashMap<>();
        params.put("token", token);
        params.put("orderId", String.valueOf(mOrderId));
        params.put("optionId", String.valueOf(mOptionId));
        params.put("goodQuantity", 1);
        params.put("rentId", String.valueOf(mRentId));
        params.put("rentQuantity", 1);
        Map<String, Object> clientInfo = new HashMap<>();
        clientInfo.put("customerName", editClientName.getText().toString());
        clientInfo.put("customerMobile", editClientPhone.getText().toString());
        clientInfo.put("receiveName", editUser.getText().toString());
        clientInfo.put("receiveMobile", editUserPhone.getText().toString());
        clientInfo.put("installAddress", addressCode);
        clientInfo.put("detailAddress", editDetailAddress.getText().toString());
        params.put("clientInfo", clientInfo);
        ApiRequestsBasis.postOrder(this, params, new ApiCallBack() {
            @Override
            public void onResponse(ResponseParams result) {
                if (result.getStatus() == HttpConfig.success) {
                    OrderInfoBean orderInfoBean = (OrderInfoBean) MapToBeanUtil.toJavaBean(result.getParams(), OrderInfoBean.class);
                    Intent intent = new Intent(ProduceOrderActivity.this, OrderDesActivity.class);
                    intent.putExtra("orderInfo", orderInfoBean);
                    intent.putExtra("imgUrl", mProImgUrl);
                    intent.putExtra("deviceName", mProName);
                    intent.putExtra("normsidName", mNormsidName);
                    startActivity(intent);
                } else {
                    Toast(result.getMessage());
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                if (NetUtils.isConnected(ProduceOrderActivity.this)) {
                    Toast(getString(R.string.service_error));
                } else {
                    Toast(getString(R.string.network_fails));
                }
            }
        });
    }


    private void checkCustomerPhone() {
        Map<String, Object> params = new HashMap<>();
        params.put("token", token);
        params.put("phone", editClientPhone.getText().toString());
        ApiRequestsBasis.checkCustomerPhone(this, params, new ApiCallBack() {
            @Override
            public void onResponse(ResponseParams result) {
                if (result.getStatus() == HttpConfig.success) {
                    boolean has = (boolean) result.getParams().get("hasBeenRecommended");
                    if (has) {
                        textPrompt.setText(result.getParams().get("msg").toString());
                    } else {
                        textPrompt.setText("");
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {

            }
        });
    }

    public void PermissionDialog() {
        Permission.getInstance(ProduceOrderActivity.this)
                .requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .results(new ResultCallBack() {
                    @Override
                    public void result(PermissionsResult result) {
                        if (result.getPermission().equals(Manifest.permission.WRITE_EXTERNAL_STORAGE) && result.isGranted()) {
                            CityChooseUtils.getInstance().setCallBack(ProduceOrderActivity.this);
                            CityChooseUtils.getInstance().toCityChoose(ProduceOrderActivity.this, "province", "city", "area");
                        } else if (result.getPermission().equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            new AlertDialog.Builder(ProduceOrderActivity.this).
                                    setTitle("帮助")
                                    .setMessage("请在设置->应用管理->力浦净水->权限管理->读写手机存储\n避免影响正常功能的使用")
                                    .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Uri packageURI = Uri.parse("package:" + getPackageName());
                                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                                            startActivity(intent);
                                        }
                                    }).setNegativeButton("取消", null).show();
                        }
                        Permission.getInstance(ProduceOrderActivity.this).unresults();
                    }
                });
    }

}
